package com.hopu.ssm_demo.service.impl;

import com.hopu.ssm_demo.dao.UserMapper;
import com.hopu.ssm_demo.entity.User;
import com.hopu.ssm_demo.entity.UserExample;
import com.hopu.ssm_demo.service.IUserService;
import com.hopu.ssm_demo.service.IUserService2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

/**
 * User业务逻辑实现
 */
@Service
public class UserServiceImpl implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void insert(User user) {
        userMapper.insertSelective(user);
    }

    @Override
    public void delete(long userId) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo((int)userId);
        example.or(criteria);
        userMapper.deleteByExample(example);
    }

    @Override
    public void update(User user) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo(user.getUserId());
        example.or(criteria);
        userMapper.updateByExample(user,example);
    }

    @Override
    public User selectById(long userId) {
        UserExample example = new UserExample();
        UserExample.Criteria criteria = example.createCriteria();
        criteria.andUserIdEqualTo((int)userId);
        example.or(criteria);
        List<User> users = userMapper.selectByExample(example);
        if(users.size() > 0)
            return users.get(0);
        return null;
    }

    @Override
    public List<User> selectAll() {
        return userMapper.selectByExample(null);
    }

    /**
     * 测试事务
     */
    @Transactional
    public void insertTest(){
        User user = new User();
        user.setUserName("成功");
        userMapper.insert1(user);
        user.setUserName("失败");
        userMapper.insert2(user);//出错
    }

    @Autowired
    private IUserService2 userService2;

    //@Transactional(propagation = Propagation.REQUIRES_NEW)
    public void insert2(){
        User user = new User();
        user.setUserName("外部事务");
        userMapper.insert2(user);
        userService2.insert1();
        //throw new RuntimeException("异常");
    }

}
